package com.cg.ai.controller;

import com.cg.ai.entity.po.ChatMessage;
import com.cg.ai.entity.po.ChatSession;
import com.cg.ai.entity.vo.ChatRequest;
import com.cg.ai.entity.vo.ChatResponse;
import com.cg.ai.entity.vo.CreateSessionRequest;
import com.cg.ai.entity.vo.ChatEntity;
import com.cg.ai.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import org.springframework.http.ResponseEntity;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
@Slf4j
public class ChatController {

    private final ChatService chatService;

    /**
     * 查询用户的会话列表，按最后活跃时间降序
     */
    @GetMapping("/sessions")
    public List<ChatSession> sessions(@RequestParam("userId") Long userId) {
        List<ChatSession> list = chatService.listSessions(userId);
        log.info("[Chat] 查询会话列表: userId={}, size={}", userId, list == null ? 0 : list.size());
        return list;
    }

    /**
     * 查询某会话下的消息列表，按消息顺序升序
     */
    @GetMapping("/messages")
    public List<ChatMessage> messages(@RequestParam("sessionId") Long sessionId) {
        List<ChatMessage> list = chatService.listMessages(sessionId);
        log.info("[Chat] 查询消息列表: sessionId={}, size={}", sessionId, list == null ? 0 : list.size());
        return list;
    }

    /**
     * 创建新会话
     */
    @PostMapping("/sessions")
    public ChatSession createSession(@RequestBody CreateSessionRequest req) {
        ChatSession session = chatService.createSession(req.getUserId(), req.getTitle());
        log.info("[Chat] 创建会话: userId={}, sessionId={}, title={}", req.getUserId(), session.getSessionId(), req.getTitle());
        return session;
    }

    /**
     * 删除指定会话，以及其下的全部消息
     */
    @DeleteMapping("/sessions/{sessionId}")
    public void deleteSession(@PathVariable("sessionId") Long sessionId) {
        log.info("[Chat] 删除会话: sessionId={}", sessionId);
        chatService.deleteSession(sessionId);
    }

    /**
     * 同步聊天：提交用户 prompt，返回完整 AI 回复
     */
    @PostMapping(value = "/chat", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ChatResponse chat(@RequestBody ChatRequest req) {
        Long userId = req.getUserId();
        Long sessionId = req.getSessionId();
        String prompt = req.getPrompt();
        ChatResponse resp = chatService.chat(userId, sessionId, prompt);
        return resp;
    }
}